<?php
namespace App\Services;

//引入两个类
use App\Enum\CityEnableEnum;
use App\Enum\CityGpsEnum;
use App\Enum\RedisEnum;
use App\Models\CityGpsModel;
use Location\Coordinate;
use Location\Polygon;
use Exception;

class MapService extends BaseService
{
    private const TENCENT_MAP_KEY='KOYBZ-SNVKQ-4635S-46YWI-JDZBF-25BUV';

    /**
     * 接口提供由经纬度到文字地址及相关位置信息的转换能力
     * https://lbs.qq.com/service/webService/webServiceGuide/webServiceGcoder
     *
     * @param $location
     * @param bool $onlyCode
     * @return mixed|string
     * @throws Exception
     */
    public static function _fetchAdcode($location, bool $onlyCode=true)
    {
        try {
            if (empty($location)) return '';
            $location = explode(',', $location);

            $baseUrl = 'https://apis.map.qq.com/ws/geocoder/v1/?location=%s&key=%s';
            $url = sprintf($baseUrl, $location[1] . ',' . $location[0], self::TENCENT_MAP_KEY);
            $result = curlGet($url);
            if ($onlyCode) {
                if ($result['status'] == 0) {
                    return $result['result']['ad_info']['adcode'];
                } else return '';
            }
            return $result;
        }catch (Exception $e){
            throw new Exception(sprintf('地址逆解析失败:%s',$e->getMessage()));
        }
    }

    /**
     *  地址解析
     *
     * @param $address
     * @param $region
     * @return mixed
     * @throws Exception
     */
    public static function addressAnalyse($address, $region)
    {
        try {
            $url = sprintf('https://apis.map.qq.com/ws/geocoder/v1/?region=%s&address=%s&key=%s', $region,$address, self::TENCENT_MAP_KEY);
            $result = curlGet($url);
            if( empty($result) || $result['status'] > 0 ) {
                if( isset($result['message'])) throw new Exception($result['message']);
                else throw new Exception("三方地图返回异常");
            }
            return $result['result'];
        }catch (Exception $exception){
            throw new Exception(sprintf('获取数据失败：%s',$exception->getMessage()));
        }
    }

    /**
     * 两点的距离
     *
     * @param string $locationA 起："经,纬"
     * @param string $locationB 止："经,纬"
     * @return mixed
     * @throws Exception
     */
    public static function distanceBetweenLocations(string $locationA, string $locationB)
    {
        try {
            $locationA = self::lngLatChange($locationA);
            $locationB = self::lngLatChange($locationB);
            $url = sprintf('https://apis.map.qq.com/ws/distance/v1/matrix?mode=driving&from=%s&to=%s&key=%s', $locationA,$locationB, self::TENCENT_MAP_KEY);

            $result = curlGet($url);
            if( empty($result) || $result['status'] > 0 ) {
                if( isset($result['message'])) throw new Exception($result['message']);
                else throw new Exception("三方地图返回异常");
            }

            return $result['result'];
        }catch (Exception $exception){
            throw new Exception(sprintf('获取数据失败：%s',$exception->getMessage()));
        }
    }

    /**
     * @param string $location
     * @return string
     * @throws Exception
     */
    private static function lngLatChange(string $location): string
    {
        try {
            if(strpos($location,',')>0){
                $tmp = explode(',', $location);
                return $tmp[1].','.$tmp[0];
            }
            throw new Exception("$location");
        }catch (Exception $e){
            throw new Exception("经纬度变位置失败:".$e->getMessage());
        }
    }
}
